/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function (root) {
  if (!root) return []

  //存放每层的最后一个元素
  let res = []
  //队列
  let queue = [root]
  while (queue.length > 0) {
    //当前层的节点个数
    let size = queue.length
    //遍历当前层的所有节点
    for (let i = 0; i < size; i++) {
      //出队
      let node = queue.shift()
      //如果当前节点是当前层的最后一个，存储节点值
      if (i === size - 1) {
        res.push(node.val)
      }
      //左右节点入队
      if (node.left) queue.push(node.left)
      if (node.right) queue.push(node.right)
    }
  }

  return res
};